package com.zhentao.filter;

import com.zhentao.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Order(-1)		// 保证请求必经此代码
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    // 匿名可访问的 url，网关过滤器其他代码省略
    private static final List<String> ANONYMOUS_URI_LIST = new ArrayList<>();

    static {
        // 注意：生产环境下面这两个要注释掉，或者用开启停用状态来确保接口文档是否可匿名访问。
        ANONYMOUS_URI_LIST.add("/doc.html");
        ANONYMOUS_URI_LIST.add("/v2/api-docs");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
//        System.err.println(request.getURI().getPath());
//        判断是否是登录
        if(request.getURI().getPath().contains("/login")){
            return chain.filter(exchange);
        }

//      获取token
        String token = request.getHeaders().getFirst("token");
//        判断token是否存在
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//      判断token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if(i == 1 ||i==2){ //过期
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            Object id = claimsBody.get("id");
            ServerHttpRequest appUserId = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("appUserId", id.toString());
            }).build();
            //            重置header
            exchange.mutate().request(appUserId).build();

        }catch (Exception e){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
